<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item prop="keywords" label="关键字">
          <el-input
            v-model="queryParams.keywords"
            placeholder="关键字"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item prop="sku" label="材料编码">
          <el-input
            v-model="queryParams.sku"
            placeholder="编码精确查询"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="仓库" prop="warehouseId">
          <el-select
            v-model="queryParams.warehouseId"
            clearable
            placeholder="仓库"
            style="width: 100px"
          >
            <el-option
              v-for="item in warehouseList"
              :key="item.id"
              :label="item.name"
              :value="item.id || ''"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="操作" prop="operation">
          <el-select v-model="queryParams.operation" clearable style="width: 100px">
            <el-option
              v-for="item in InventoryOperation"
              :key="item"
              :label="InventoryOperation_LABEL[item]"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item class="search-buttons">
          <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
          <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="hover" class="data-table">
      <div class="data-table__toolbar">
        <div class="data-table__toolbar--actions">
          <el-button type="primary" plain icon="plus" @click="gotoOperation('in')">
            材料入库
          </el-button>
          <el-button type="primary" plain icon="remove" @click="gotoOperation('out')">
            材料出库
          </el-button>
        </div>
      </div>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableDatas"
        highlight-current-row
        border
        class="data-table__content"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="仓库名称" prop="warehouseName" width="150" />
        <el-table-column label="标题" prop="title" width="150" />
        <el-table-column label="操作" prop="operation" width="80">
          <template #default="scope">
            {{ InventoryOperation_LABEL[scope.row.operation] }}
          </template>
        </el-table-column>
        <el-table-column label="操作人" align="center" min-width="150" prop="username" />
        <el-table-column label="时间" align="center" min-width="150" prop="operationTime" />
        <el-table-column label="描述" align="center" min-width="150" prop="remark" />
        <el-table-column label="物流" align="center" min-width="150" prop="deliveryNo" />
        <el-table-column fixed="right" label="操作">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              icon="search"
              @click="handleOpenDialog(scope.row)"
            >
              明细
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="fetchData"
      />
    </el-card>

    <!-- 客户表单弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="800px"
      height="300px"
      @close="handleCloseDialog"
    >
      <el-table :data="dataDetail?.items" highlight-current-row border class="data-table__content">
        <el-table-column label="名称" prop="name" width="150" />
        <el-table-column label="编码" prop="sku" width="150">
          <template #default="scope">
            <span v-if="queryParams.sku == scope.row.sku" :style="'color: red'">
              {{ scope.row.sku }}
            </span>
            <span v-else>{{ scope.row.sku }}</span>
          </template>
        </el-table-column>
        <el-table-column label="数量" prop="quantity" width="80" />
        <el-table-column label="市场价格" prop="price" width="80">
          <template #default="scope">
            {{ scope.row.price + "元" }}
          </template>
        </el-table-column>
        <el-table-column label="成本价" prop="price" width="80">
          <template #default="scope">
            {{ scope.row.costPrice + "元" }}
          </template>
        </el-table-column>
        <el-table-column label="单位" prop="unit" width="80" />
        <el-table-column label="规格" prop="spec" width="150" />
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from "vue";
import router from "@/router";
import type { ElTable } from "element-plus";
import WarehouseAPI, { WarehousePageVO } from "@/api/business/warehouse/warehouse.api";
import {
  InventoryOperation_LABEL,
  InventoryOperation,
} from "@/api/business/warehouse/warehouseEnum";
import InventoryRecordAPI, {
  InventoryRecordPageQuery,
  InventoryRecordPageVO,
} from "@/api/business/warehouse/inventoryRecord.api";

defineOptions({
  name: "InventoryRecord",
  inheritAttrs: false,
});

const queryFormRef = ref();
const dataTableRef = ref<InstanceType<typeof ElTable>>();

const loading = ref(false);
const total = ref(0);
const warehouseList = reactive<WarehousePageVO[]>([]);

const queryParams = reactive<InventoryRecordPageQuery>({
  pageNum: 1,
  pageSize: 10,
});

// 客户表格数据
const tableDatas = ref<InventoryRecordPageVO[]>();
// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
});

const dataDetail = ref<InventoryRecordPageVO>({
  items: [],
});

function gotoOperation(type?: string) {
  if (type == "out") {
    router.push({
      path: "/warehouse/outOperation",
      query: { title: "材料出库" },
    });
  } else {
    router.push({
      path: "/warehouse/inOperation",
      query: { title: "材料入库" },
    });
  }
}

async function handleOpenDialog(record: InventoryRecordPageVO) {
  await InventoryRecordAPI.getFormData(record.id || "0")
    .then((data) => {
      Object.assign(dataDetail, data);
      dataDetail.value.items?.push(...(data.items || []));
      dialog.title = record.title || "详情";
      if (record.operation) {
        dialog.title += "(" + InventoryOperation_LABEL[record.operation] + ")";
      }
    })
    .finally(() => {
      dialog.visible = true;
    });
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  dataDetail.value = { items: [] };
}

// 获取数据
function fetchData() {
  loading.value = true;
  InventoryRecordAPI.getPage(queryParams)
    .then((data) => {
      tableDatas.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

// 查询（重置页码后获取数据）
function handleQuery() {
  queryParams.pageNum = 1;
  fetchData();
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  fetchData();
}

const loadWarehouses = () => {
  WarehouseAPI.loadAll().then((data) => {
    if (data.length > 0) {
      warehouseList.push(...data);
    }
  });
};

onMounted(() => {
  loadWarehouses();
  handleQuery();
});
</script>
